<?php
/**
 * 前台支付管理
 * @author cjli
 *
 */
class PaymentAction extends HomeAction
{
	
	//支付返回
	public function callback()
	{
		global $user,$language_id;
		C('TMPL_ACTION_ERROR', THEMES_PATH.'public/paymentFailed.phtml'); // 变更错误提示地址
//		$_POST = array(
//			'mc_gross' => '330.75',	//支付金额
//			'txn_id' => 'Paypal',		//paymentId
//			'invoice' => 'loca201303270001', //订单号
//			'payment_status' => 'Completed', //Completed,Pending
//		);
		$post = array_merge($_POST, $_GET);
		Log::write('pay log:'.json_encode($post));
		$payment_method = trim($post['pay']);
		import('COM.Payment');
		$paymentInstance = Payment::getInstance($payment_method);

		if(!is_object($paymentInstance)){
			$this->error(L('_PAYMENT_ERROR_'), url(''));
		}
		if ($paymentInstance instanceof Payment_Interface) {
        $return = $paymentInstance->callback();
        $order_sn = $return['orderNumber'];
        
        $orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
        //支付后跳转的url
        $jumpUrl =  'order/query/order_sn/'.$order_sn;
        if(UserModel::logged()){
        	if($user['is_partner'] == 1){
        		$jumpUrl = "partner";
        	}else{
                $jumpUrl = "user";
        	}
        	if($orderInfo){
        		$jumpUrl .=  '/order_info/oid/'.$orderInfo['id'];
        	}else{
        		$jumpUrl .=  '/order_list';
        	}      
        }
        $jumpUrl_js = "javascript:top.location.href='http://".$_SERVER['HTTP_HOST']."/".$jumpUrl."';";

		//支付成功
	      if ($return['updateOrderStatus'] && $return['verified']){
              
              $return['syncPaypal']   = ($post['pay'] == 'Paypal' ? true : false);
              $return['syncWorldpay'] = ($post['pay'] == 'Worldpay' ? true : false);
	      	//充值
		      if('recharge_' == substr($order_sn,0,9) && is_numeric($account_id = substr($order_sn,9))){
		       
		      	
		      }
		      //订单支付
		      elseif (true === ($payment_callback_res = $this->payment_callback($return))) {
			      //$orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
			      if(!$orderInfo){
			      	$this->error(L('_ORDER_NO_EXIST_'), url(''));
			      }
			      if (isset($return) && $return['verified'])
			      {

			      	$arguments['oid'] = $orderInfo['id'];
			      	if(isset($return['message']) && $return['message']){
			      		$arguments['message'] =$return['message'];
			      	}
			      	$arguments['sign'] = MD5($arguments['oid'].C('pwd_key'));

			      	$visa_jump_js = "javascript:top.location.href='".url('cart/callback').'?'.http_build_query($arguments)."';";
					if(ucwords($payment_method) == 'Visabill'){
			      		$this->success($return['message'].' ', $visa_jump_js); //code 001
					}else{
						$this->success($return['message'].' ', url('cart/callback').'?'.http_build_query($arguments)); //code 001
					}
			        exit;
			      } else {
			      	 OrderModel::payment_insertOrdersLog($orderInfo,$return); //添加订单日志
			         $this->error(L('_ORDER_PAYMENT_FAILURE_').' ', $jumpUrl_js, '', 5); //code 002
			      }
		      }else{
				 $error_str = L('_ORDER_PAYMENT_FAILURE_');
				 if($payment_callback_res == -4){
				     $error_str = L('_ORDER_PAYMENT_PAYPAL_TIPS_');
					 $return['returnMsg'] = 'paypal 同步返回时 订单为未支付状态';
				 }
		      	 //OrderModel::payment_insertOrdersLog($orderInfo,$return); //添加订单日志
		      	 $this->error($error_str.' ', $jumpUrl_js, '', 5);//code 003
		      }
	      	
	      }else{
                Log::write('pay false log:'.json_encode($return));
				OrderModel::payment_insertOrdersLog($orderInfo,$return); //添加订单日志
	      	    $this->error($return['message'].' ', $jumpUrl_js, '', 5);//code 004 //给error设定一个足够大的时间，防止支付错误跳转
	      }
      
      //充值
      if('recharge_' == substr($order_sn,0,9) && is_numeric($account_id = substr($order_sn,9))){
        $return_account = 	$this->account_callback($account_id, $return);
      	if($return_account){
      		$this->success(L('_RECHARGE_SUCCESS_'), url(''));
      	}else{
      		$this->error(L('_RECHARGE_FAILURE_'), url(''));
      	}
      }else{
      
	      //支付状态成功
	      if ($return['updateOrderStatus'] && true === $this->payment_callback($return)) {
	        //TODO支付成功预处理
	      }
	      $orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
	      if(!$orderInfo){
	      	$this->error(L('_ORDER_NO_EXIST_'), url(''));
	      }
	      if (isset($return) && $return['verified'])
	      {
	        //支付通知邮件
	      	$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
					if($email_template){
						$mailInstance = new EmailModel();
						$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
						$title = $mailInstance->replaceMail($email_template['title']);
						$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
					}
	        
	      	$arguments['oid'] = $orderInfo['id'];
	      	if(isset($return['message']) && $return['message']){
	      		$arguments['message'] =$return['message'];
	      	}
	      	$this->success($return['message'].'code 005', url('cart/callback', $arguments));
	        
	      } else {
	         $this->error(L('_ORDER_PAYMENT_FAILURE_'), url(''));
	      }
      }
    } else {
      $this->error(L('_PAYMENT_NOT_EXIST_'), url(''));
    }
  
    
	}
	
	public function notice()
	{
		$post = array_merge($_POST, $_GET);
		Log::write('pay notice log:'.json_encode($post));
		$payment_method = trim($post['pay']);
		import('COM.Payment');
		$paymentInstance = Payment::getInstance($payment_method);
		if(!is_object($paymentInstance)){
			$this->error(L('_PAYMENT_ERROR_'), url(''));
		}
		if ($paymentInstance instanceof Payment_Server_Interface) {
			$return = $paymentInstance->serverCallback();
			if (isset($return) && $return['verified']) {
				if ($return['updateOrderStatus'] && true === $this->payment_callback($return)) {
				    //TODO成功处理
					if($payment_method == 'Worldpay'){
						Log::write('pay log: notice TODO success=>'.$payment_method);
						echo '[OK]';exit;
					}
				}
			}else{
				$orderInfo = OrderModel::get_oreder_info_by_order_sn($return['orderNumber']);
				OrderModel::payment_insertOrdersLog($orderInfo,$return); //添加订单日志
			}
	    } else {
	      // TODO 通知接口无效
	    }
	}
	
	//支付失败
	public function fail()
	{
    echo '<h1>ERROR</h1>';
    var_dump($_GET, $_POST);
	}
	
	/**
   * 支付后调用 callback 函数
   * @param array $result 返回结果
   */
	private function payment_callback($result = array())
	{
        global $user,$language_id;
		$order_sn = $result['orderNumber'];
        if ($result['verified'] == 1) {
            $orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
            //如果订单状态已经是支付完成状态，则直接返回TRUE
            if( $orderInfo['payment_status'] == OrderModel::PAY_PAYED ){
                return true;
            }else if($result['syncPaypal'] || $result['syncWorldpay']){
                return -4;
            }

            $pay_amount = currency($orderInfo['pay_amount'], null, false, $result['currency']);
            if ($result['paidAmount'] != $pay_amount) {
                Log::write('payment error:'.$order_sn.'金额不符合 真实支付金额:'.$result['currency'].$result['paidAmount'].'
                    实际订单金额:'.$result['currency'].$pay_amount);
                return -2;
            }
            if (OrderModel::update_order_status($orderInfo['id'], array('payment_status' => OrderModel::PAY_PAYED, 'order_status' => OrderModel::ORDER_CONFIRMED))) {
                //保留交易流水号
                if(isset($result['paymentId']) && $result['paymentId']){
                    $order_db = D('orders');
                    $order_db->where('id='.$orderInfo['id'])->save(array('payOrderNum' => $result['paymentId']));
                }
                //送积分
                OrderModel::send_order_points($orderInfo['id']);

                //支付通知邮件
               /* $email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
                if($email_template){
                    $mailInstance = new EmailModel();
                    $content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
                    $title = $mailInstance->replaceMail($email_template['title']);
                    $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
                }*/
                //支付通知短信
                $ShortMessage=A("ShortMessage");
                $short_mesg_result=$ShortMessage->send_message('SMS_4725607',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'"}');
                //发送短信记录写入日志
                if($short_mesg_result){
                    Log::write('支付短信，订单号'.$orderInfo['order_sn'].'，在线支付，订单金额：'.$orderInfo['order_amount'].'，时间：'.date("Y-m-d H:i:s",time()));
                }
                //  商品金额超过399  反给推荐人100现金
                if($orderInfo&&$orderInfo['product_amount']>=399&&$orderInfo['coupon_code']){
                    UserModel::get_money_friend($orderInfo['coupon_code']);
                }
                return true;
            }else{
                return -3;
            }
        } else {
            Log::write('payment error not verified');
            return -1;
        }
	}
	
	/**
	 * 充值支付
	 * @param int $account_id 充值ID
	 * @param array $result 返回结果
	 */
	private function account_callback($account_id, $result = array())
	{
		$user_account_db = D('user_account');
		$user_account_db->field('id,amount,payment,user_id');
		$accountInfo = $user_account_db->where('user_account.id='.$account_id)->find();
		if(!$accountInfo){
			return -1;
		}
		$paymentInfo = PaymentModel::get_payment_info($accountInfo['payment']);
		$payment_fee = PaymentModel::get_paymeent_fee($accountInfo['payment'], $accountInfo['amount']);
		$pay_amount = $accountInfo['amount'] + $payment_fee;
		if($result['paidAmount'] != $pay_amount){
			return -2;
		}
		//自动修改充值结果
		if(C('is_user_account_true')){
			$data = array(
				'paid_time' => time(), 
				'is_paid' => 1,
				'admin_note' => L('_RECHARGE_SUCCESS_'),
			);
			$user_account_db->where('id='.$account_id)->save($data);
			UserModel::log_account_change($accountInfo['user_id'], $accountInfo['amount'],0,0,0,L('_RECHARGE_'), UserModel::ACT_SAVING);
		}
		return true;
	}



    /**
     * 获取支付手续费
     * @param string $paymentname 支付方式名称
     * @param float $total_fee 支付总费用
     */
    public function getPaymentMoney1($paymentname,$amount,$partner=0,$weight = 0){
        //支付信息
        return  $paymentFee = PaymentModel::get_paymeent_fee($paymentname, $amount,$partner,$weight);
    }
    public function getPaymentMoney()
    {
        $paymentname =$_GET['payment_method']?trim($_GET['payment_method']):null;
        $amount = floatval($_GET['amount']);
        $paymentFee= $this->getPaymentMoney1($paymentname,$amount);
        echo $paymentFee;
    }
    //合作伙伴计算附加费用
    public function getPaymentMoney_partener(){
        global $user;
        $paymentname =$_REQUEST['payment_method']?trim($_REQUEST['payment_method']):null;
        $amount = isset($_REQUEST['amount'])?floatval($_REQUEST['amount']):0.00;
        $weight=isset($_REQUEST['weight'])?$_REQUEST['weight']:0;
        $paymentFee['paymentfee']= $this->getPaymentMoney1($paymentname,$amount,1,$weight);
        $discount = UserModel::get_rank_discount($user['rank_id']);
        $paymentFee['discount_rate']= $discount;
        echo json_encode($paymentFee);
    }
	/**
	 * 获取配送费用
	 * @param int $shipping_method 配送方式名称
	 * @param int $area_id	配送地区ID
	 * @param int $weight 商品重量
	 */
    public function getShippingMoney1($shipping_method, $area_id, $goods_amount, $weight, $goods_number){
        global $user;
        if($user['id']){
            $where['a.user_id'] = $user['id'];
        }
        if(!$user['id']){
            $where['a.sid'] = $user['sid'];
        }
        $info = M('cart_products as a ')->field('b.catid')->join('product as b on a.pid = b.id')->where($where)->group('b.catid')->select();
        if($info[0]['catid'] == 2121 && count($info) == 1){//充值卡 giftcard 免邮费
            return 0; exit;
        }

        return  $shipping_fee = ShippingModel::get_shipping_fee($shipping_method, $area_id, $goods_amount, $weight,null, $goods_number);
    }
	public function getShippingMoney()
	{
		$shipping_method = trim($_GET['shipping_method']);
		$area_id = intval($_GET['area_id']);
		$weight = intval($_GET['weight']);
		$goods_amount = floatval($_GET['amount']);
		$goods_number = intval($_GET['number']);
        $shipping_fee= $this->getShippingMoney1($shipping_method, $area_id, $goods_amount, $weight, $goods_number);
		echo $shipping_fee;
	}
	/**
	 * 使用余额支付
	 */
	public function getSurplusMoney()
	{
		global $user;
		$price = 0;
		$amount = floatval($_GET['amount']);
		if(isset($user['user_money']) && $user['user_money']>0){
			if($amount<$user['user_money']){
				$price = $amount;
			}else{
				$price = $user['user_money'];
			}
		}
		echo $price;exit;
	}
	
	/**
	 * 使用积分支付
	 */
	public function getIntegralMoney()
	{
		global $user;
		$amount = floatval($_GET['amount']);
		$integral = intval($_GET['integral']);
		if($integral==0 || $amount == '0.0'){
			exit(0);
		}
			$use_integral = UserModel::get_user_integral($amount);
			if(is_array($use_integral)){
				list($total_integral, $integral_money) = $use_integral;
				$integral =$total_integral<$integral ? $total_integral : $integral;
				//可抵消的价格
				$integral_money = $integral*intval(C('integral_percent'))/100;
				echo $integral_money;exit;
			}
			else{
				exit(0);
			}
	}
	
	/**
	 * 使用红包支付
	 */
	public function getBonusMoney()
	{
		global $user;
		$price = 0;
		$amount = floatval($_GET['amount']);
		$amount -= CartModel::special_total_amount(); //减去特殊商品总金额
		
		$id = intval($_GET['id']);
		if($id==0 || $amount == '0.0'){
			exit(0);
		}
		$user_bonus = UserModel::get_bonus_info($id);
		if(isset($user_bonus['type_money']) && $user_bonus['type_money']>0){
			$price = $user_bonus['type_money'];
			if( (floatval($amount)-floatval($price)) <= 0){
			    exit(0);
			}
		}
		else{
			exit(0);
		}
		echo $price;exit;
	}

    /**
    * Visabill
    */
    public function Visabill(){
       
		$site = $_REQUEST['sitename'];
		if ($site != 'www.google.fr'){
			echo ("<p align='center'>ErrorCode: 2001. Contactez-nous  pour le paiement anormal. service@ownonly.com / Payment abnormal, please contact us. service@ownonly.com</p>");
		    exit;
		}
		//$language = $_REQUEST['language'];
		$language = $_COOKIE['think_language'];
		$merNo = $_REQUEST['merNo'];
		$gatewayNo = $_REQUEST['gatewayNo'];
		$signInfo = $_REQUEST['signInfo'];
		$paymentMethod = $_REQUEST['paymentMethod'];
		$orderCurrency = $_REQUEST['orderCurrency'];
		$orderNo = $_REQUEST['orderNo'];
		$orderAmount = $_REQUEST['orderAmount'];
		$returnUrl = $_REQUEST['returnUrl'];
		$remark = $_REQUEST['remark'];
		$firstName = $_REQUEST['firstName'];
		$lastName = $_REQUEST['lastName'];
		$email = $_REQUEST['email'];
		$phone = $_REQUEST['phone'];
		$country = $_REQUEST['country'];
		$state = $_REQUEST['state'];
		$city = $_REQUEST['city'];
		$address = $_REQUEST['address'];
		$zip = $_REQUEST['zip'];

		$this->assign('sitename', $site);
        $this->assign('language', $language);
        $this->assign('merNo', $merNo);
        $this->assign('gatewayNo', $gatewayNo);
        $this->assign('signInfo', $signInfo);
        $this->assign('paymentMethod', $paymentMethod);
        $this->assign('orderCurrency', $orderCurrency);
        $this->assign('orderNo', $orderNo);
        $this->assign('orderAmount', $orderAmount);
        $this->assign('returnUrl', $returnUrl);
        $this->assign('remark', $remark);
        $this->assign('firstName', $firstName);
        $this->assign('lastName', $lastName);
        $this->assign('email', $email);
        $this->assign('phone', $phone);
        $this->assign('country', $country);
        $this->assign('state', $state);
        $this->assign('city', $city);
        $this->assign('address', $address);
        $this->assign('zip', $zip);

		if($language){		
			$langs = (array)json_decode(file_get_contents('http://'.$_SERVER['HTTP_HOST'].'/index/lang/name/'.$language.''));
		}else{
			$langs = (array)json_decode(file_get_contents('http://'.$_SERVER['HTTP_HOST'].'/index/lang/'));
		}

		$txtorderinfo		=$langs['orderdetailed'];
		$txtorderon			=$langs['_THE_ORDER_NUMBER_IS_'];
		$txtorderbz			=$langs['currency'];
		$txtorderamount		=$langs['recharge_ampount'];
		$txtbillinfo		=$langs['delivery_billing_info']; 
		$txtbillfname		=$langs['fristname'];
		$txtbilllname		=$langs['lastname'];
		$txtbilladdress		=$langs['address'];
		$txtbillcountry		=$langs['couny'];
		$txtbillselect		=$langs['xuanze'];
		$txtbillstate		=$langs['state'];
		$txtbillcity		=$langs['city'];
		$txtbillzip			=$langs['postcode'];  
		$txtbillemail		=$langs['email'];
		$txtbillphone		=$langs['userphone'];
		$txtbillchange		=$langs['edit_address'];
		$txtconfim			=$langs['saveuser'];
		$txtcancel			=$langs['cancel'];
		$txtusexyk			=$langs['payment_info'];
        
        $this->assign('txtorderinfo', $txtorderinfo);
        $this->assign('txtorderon', $txtorderon);
        $this->assign('txtorderbz', $txtorderbz);
        $this->assign('txtorderamount', $txtorderamount);
        $this->assign('txtbillinfo', $txtbillinfo);
        $this->assign('txtbillfname', $txtbillfname);
        $this->assign('txtbilllname', $txtbilllname);
        $this->assign('txtbilladdress', $txtbilladdress);
        $this->assign('txtbillcountry', $txtbillcountry);
        $this->assign('txtbillselect', $txtbillselect);
        $this->assign('txtbillstate', $txtbillstate);
        $this->assign('txtbillcity', $txtbillcity);
        $this->assign('txtbillzip', $txtbillzip);
        $this->assign('txtbillemail', $txtbillemail);
        $this->assign('txtbillphone', $txtbillphone);
        $this->assign('txtbillchange', $txtbillchange);
        $this->assign('txtconfim', $txtconfim);
        $this->assign('txtcancel', $txtcancel);
        $this->assign('txtusexyk', $txtusexyk);

		$jspush = 'var consignee_not_null = "'.$langs['input_contact_name'].'";'."\n";
		$jspush .= 'var consignee_not_righ = " Name:Please input between 2-500 characters only!";'."\n";
		$jspush .= 'var address_not_null = "'.$langs['inputaddress'].'";'."\n";
		$jspush .= 'var address_not_righ = " Address:Please input between 2-500 characters only!";'."\n";
		$jspush .= 'var country_not_null = "'.$langs['choosecountry'].'";'."\n";
		$jspush .= 'var province_not_null = "'.$langs['inputstate'].'";'."\n";
		$jspush .= 'var city_not_null = "'.$langs['inputcity'].'";'."\n";
		$jspush .= 'var city_not_righ = " City:Please input between 2-100 characters only!";'."\n";
		$jspush .= 'var zip_not_num = "'.$langs['inputpostcode'].'";'."\n";
		$jspush .= 'var invalid_email = "'.$langs['inputemail'].'";'."\n";
		$jspush .= 'var tele_not_null = "'.$langs['inputphone'].'";'."\n";
		$jspush .= 'var tele_invaild = "Please enter valid phone No.";'."\n";
        $this->assign('jspush', $jspush);

		$real_ip = real_ip();
		$this->assign('real_ip', $real_ip);

		$wfbillno=fopen($_SERVER['DOCUMENT_ROOT'] . "/visabillgateway.log","a+");
		fwrite($wfbillno,date("Y-m-d H:i:s")."|orderNo[ ".$orderNo." ]|orderAmount[ ".$orderAmount." ]|orderCurrency[ ".$orderCurrency." ]|signInfo[ ".$signInfo." ]|real_ip[ ".$real_ip." ]"."\r\n");
		fclose($wfbillno);

		$this->display('Visabill');
    }

}